package com.sspku.weinotes.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sspku.weinotes.emailUtils.EmailModel;
import com.sspku.weinotes.emailUtils.SendEmail;
import com.sspku.weinotes.entity.User;
import com.sspku.weinotes.exception.IncorrectParameterException;
import com.sspku.weinotes.exception.NoSuchIdException;
import com.sspku.weinotes.exception.UserAlreadyExistsException;
import com.sspku.weinotes.exception.UserDoesNotExistException;
import com.sspku.weinotes.service.UserService;
import com.sspku.weinotes.mapper.UserMapper;
import com.sun.org.omg.SendingContext._CodeBaseImplBase;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.mail.MessagingException;
import java.util.*;

/**
* @author user
* @description 针对表【user】的数据库操作Service实现
* @createDate 2022-12-25 22:20:08
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private static final String REG_SESSION_ATTRIBUTE = "code";

    private static final String FORGET_SESSION_ATTRIBUTE = "forgetCode";

    private static final String FORGET_SESSION_ATTRIBUTE_MAP_CODE = "code";

    private static final String FORGET_SESSION_ATTRIBUTE_MAP_VCODE = "vCode";

    private static final String FORGET_SESSION_ATTRIBUTE_MAP_USERNAME = "username";
     @Autowired
    private UserMapper userMapper;
    //注册时获取验证码
    @Override
    public int registeredUser(String name, String username, String password, String code) throws IncorrectParameterException {
        //return null;
        if ((int) ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getSession().getAttribute(REG_SESSION_ATTRIBUTE) == Integer.parseInt(code)) {
            User user = new User();
           // user.setId(UUID.randomUUID().toString());
            user.setGmtCreate(new Date());
            user.setGmtModified(new Date());
            user.setUsername(username);
            user.setPassword(password);
            user.setUname(name);
            return userMapper.insert(user);

        } else { //验证码错误
           throw new IncorrectParameterException("验证码错误");
        }
    }
   //注册前获取验证码
    @Override
    public void getCode(String email) throws Exception {
        if (userMapper.findByUsername(email) != null) {
            logger.info("user " + email + " already exists");
            throw new UserAlreadyExistsException("用户已经存在,重复注册");
        } else {
            int code = (int) ((Math.random() * 9 + 1) * 1000);
            ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getSession().setAttribute(REG_SESSION_ATTRIBUTE, code);
            SendEmail.sendEmail(new EmailModel("微记验证码邮件","您的验证码是:"+code,email));
        }
    }

    @Override
    public Integer forgetPasswordGetCode(String email) throws Exception {
        if (userMapper.findByUsername(email) == null) {
            throw new UserDoesNotExistException("用户不存在");
        } else {
            int code = (int) ((Math.random() * 9 + 1) * 1000); //验证码
            int vCode = (int) ((Math.random() * 9 + 1) * 1000);//密钥
            Map<String, Object> map = new HashMap<>(3);
            map.put(FORGET_SESSION_ATTRIBUTE_MAP_CODE, code);
            map.put(FORGET_SESSION_ATTRIBUTE_MAP_VCODE, vCode);
            map.put(FORGET_SESSION_ATTRIBUTE_MAP_USERNAME, email);
            ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getSession().setAttribute(FORGET_SESSION_ATTRIBUTE, map);
          //  EmailUtils.sendEmail(email, "云舒云笔记重置密码验证码邮件", "您的验证码是:" + code);
            SendEmail.sendEmail(new EmailModel("重置密码邮件","您的验证码是:"+code,email));
            return vCode;
        }
    }
   //忘记密码，修改新密码
    @Override
    public User forgetPassword(String code, String vCode, String password) throws IncorrectParameterException, UserDoesNotExistException {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getSession().getAttribute(FORGET_SESSION_ATTRIBUTE);
        if (!map.get(FORGET_SESSION_ATTRIBUTE_MAP_CODE).toString().equals(code) || !map.get(FORGET_SESSION_ATTRIBUTE_MAP_VCODE).toString().equals(vCode)) {
            logger.info("Verification code or key error");
            throw new IncorrectParameterException("验证码或密钥错误");
        } else {
            String username = (String) map.get(FORGET_SESSION_ATTRIBUTE_MAP_USERNAME);
            User user = userMapper.findByUsername(username);
            if (user == null) {
                throw new UserDoesNotExistException("用户不存在");
            }
            user.setPassword(password);
            int f=userMapper.updateById(user);
            if(f==0) return null;
            else return user;
        }
    }

    @Override
    public User changeUserProfile(Integer uid, String name, String password) throws NoSuchIdException, IncorrectParameterException {
        User user=userMapper.selectById(uid);
        if (user==null) throw new NoSuchIdException("用户id不存在");
        if (StringUtils.isBlank(name)) {
           throw new IncorrectParameterException("名字不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new IncorrectParameterException("密码不能为空");
        }
        user.setUname(name);
        user.setPassword(password);
        user.setGmtModified(new Date());
        int res=userMapper.updateById(user);
        if(res==0) return null;
        return user;
    }
}




